package com.jthinker.web.filter;

import com.jthinker.bean.vo.Constant;
import com.jthinker.bean.vo.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * User: Gang Chen
 * Date: 2015/4/16 21:15
 */
public class LoginFilter implements Filter
{
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {
        LOGGER.info("{} init...", LoginFilter.class);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute(Constant.SESSION_USER);

        if (userInfo == null)
        {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.sendRedirect(request.getContextPath() + Constant.URL_LOGIN);
        }
        else
        {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy()
    {
        LOGGER.info("{} destory...", LoginFilter.class);
    }
}
